package com.apexedu.eas.util;

import com.apexedu.eas.exception.EasException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

/**
 * Jaskson工具类
 * Created with IntelliJ IDEA.
 * User: ly
 * Date: 13-11-27
 * Time: 下午2:10
 * To change this template use File | Settings | File Templates.
 */
public class JasksonUtil {
	private static ObjectMapper mapper = new ObjectMapper();

	static {
		mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
	}

	/**
	 * 把JSON字符串转成对象
	 *
	 * @param jsonString json字符串
	 * @param clazz      类
	 * @return 对象
	 * @throws EasException 抛出异常
	 */
	public static <T> T getDTO(String jsonString, Class<T> clazz) throws EasException {
		try {
			return mapper.readValue(jsonString, clazz);
		} catch (Exception e) {
			throw new EasException(EasException.UNKNOWN_SERVICE_ERROR, e.getMessage());
		}
	}

	/**
	 * 把对象转换成json字符串
	 *
	 * @param object 对象
	 * @return json字符串
	 * @throws EasException
	 */
	public static String getJSONString(Object object) throws EasException {
		try {
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			throw new EasException(EasException.UNKNOWN_SERVICE_ERROR, e.getMessage());
		}
	}
}
